package com.bolt.auth.security.common.utils;

import com.bolt.auth.security.common.model.AuthUserDetails;
import com.bolt.convention.exception.ServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * Created by Administrator on 2019/9/19.
 */
public class SecurityUtils {


    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取用户
     */
    public static AuthUserDetails getUser(Authentication authentication) {

        if (authentication == null) {
            throw new ServiceException("当前登录状态过期");
        }
        if (authentication.getPrincipal() instanceof AuthUserDetails) {
            AuthUserDetails userDetails = (AuthUserDetails) authentication.getPrincipal();
            return userDetails;
        }
        throw new ServiceException("找不到当前登录的信息");

    }

    /**
     * 获取用户
     */
    public static AuthUserDetails getUser() {
        Authentication authentication = getAuthentication();
        if (authentication == null) {
            return null;
        }
        return getUser(authentication);
    }


}

 